<template>
  <div class="app-container" style="display: flex; justify-content: center" v-loading="loading">
    <div style="width: 50%;min-width: 800px">
      <div style="text-align: center; margin-top: 30px; ">
        <span style="font-size: 24px;color: #000000; font-weight: bold">{{ data.taskTitle }}</span>
      </div>
      <div style="margin: 40px 0 20px 0">
        <span v-html="data.description" style="font-size: 14px; color: #666666"/>
      </div>

      <div>
        <div v-for="(item, index) in questions" :key="index">
          <div>
            <span style="font-size: 18px; color: #000000">{{ num[index] }}、{{ item.label }}</span>
          </div>
          <div v-for="(q, index) in item.questions" :key="index" style="margin: 10px; font-size: 16px">
            <div style="margin-bottom: 5px; margin-top: 20px">
              {{ index + 1 }}、{{ q.topic }}<span style="margin-left: 5px; color: orange">（{{ q.score }}分）</span>
            </div>
            <div>
              <div v-if="q.type === '1'">
                <el-radio-group v-model="q.answer" class="direction">
                  <el-radio v-for="(o, oIndex) in JSON.parse(q.options)" :key="oIndex" :label="o.value"
                            style="margin: 5px 0">{{
                      o.value
                    }}.{{ o.label }}
                  </el-radio>
                </el-radio-group>
              </div>
              <div v-if="q.type === '2'">
                <el-checkbox-group v-model="q.answer" class="direction">
                  <el-checkbox v-for="(o, oIndex) in JSON.parse(q.options)" :key="oIndex" :label="o.value"
                               style="margin: 5px 0">{{
                      o.value
                    }}.{{ o.label }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              <div v-if="q.type === '3'">
                <el-radio-group v-model="q.answer" class="direction">
                  <el-radio v-for="(o, oIndex) in JSON.parse(q.options)" :key="oIndex" :label="o.value"
                            style="margin: 5px 0">{{
                      o.label
                    }}
                  </el-radio>
                </el-radio-group>
              </div>
              <div v-if="q.type === '4'" style="margin-left: 10px">
                <div style="margin: 5px 0; display: flex; align-items: center"
                     v-for="(item, iIndex) in q.answer.length" :key="iIndex">
                  <span style="width: 60px">第{{ item }}空：</span>
                  <el-input size="mini" v-model="q.answer[iIndex]" :placeholder="`请输入第${item}空的答案`"/>
                </div>
              </div>
              <div v-if="q.type === '5'">
                <html-editor :value="null" @update:input="($e) => {getShortAnswer($e, q)}"/>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="questionView">
      <div style="border-radius: 5px; box-shadow: #666666 2px 2px 10px; font-size: 12px; padding: 10px">
        <div v-for="(item, index) in questions" :key="index">
          <div>
            <span>{{ num[index] }}、{{ item.label }}</span>
          </div>
          <div style="margin: 5px 0; display: flex; flex-wrap: wrap;">
            <div v-for="(q, index) in item.questions" :key="index" class="question"
                 :style="checkBg(q)">
              {{ index + 1 }}
            </div>
          </div>
        </div>
      </div>
      <el-button type="primary" style="width: 100%; margin-top: 20px" @click="submit()" :loading="submitLoading">
        提交试卷
      </el-button>
    </div>
  </div>
</template>

<script>
import {testPaperInfo} from "@/api/exam/testPaper";
import HtmlEditor from "@/components/HtmlEditor/index.vue";
import {getNow, testTaskSubmit} from "@/api/exam/testTask";

export default {
  name: 'exam',
  dicts: ['exam_question_type'],
  components: {HtmlEditor},
  data() {
    return {
      loading: true,
      taskId: null,
      num: ['一', '二', '三', '四', '五'],
      data: {},
      questions: [],
      startTime: '',
      submitLoading: false
    }
  },
  created() {
    this.taskId = this.$route.query.taskId
    const testPaperId = this.$route.query.testPaperId
    testPaperInfo(testPaperId, 2, {taskId: this.taskId}).then(res => {
      getNow().then(res => {
        this.startTime = res
      })
      this.data = res.data
      this.dict.type.exam_question_type.forEach(d => {
        let questions = this.data.questions.filter(q => q.type === d.value)
        if (questions.length > 0) {
          if (d.value === '2') {
            questions.forEach(i => {
              i.answer = []
            })
          }
          if (d.value === '4') {
            questions.forEach(i => {
              const tLength = i.topic.split('【填空】').length - 1
              let answer = []
              for (let i = 0; i < tLength; i++) {
                answer.push("")
              }
              i.answer = answer
              const reg = /【填空】/ig;
              i.topic = i.topic.replace(reg, "________")
            })
          }
          this.questions.push({
            label: d.label,
            questions
          })
        }
      })
      this.loading = false
    })
  },
  methods: {
    getShortAnswer(e, q) {
      q.answer = e
    },
    checkAnswersNotEmpty(questionsArray) {
      console.log("questionsArray", questionsArray)
      return !questionsArray.some(section =>
        section.questions.some(question => {
          if (question.type === '2') {
            return question.answer.length === 0;
          }
          if (question.type === '4') {
            return question.answer.some(answer => answer === '');
          }
          if (question.type === '5' || question.type === '1' || question.type === '3') {
            return question.answer === null || question.answer.trim() === '';
          }
          return false;
        })
      );
    },
    submit() {
      this.submitLoading = true
      // 校验试题是否全部完成
      // 调用校验函数
      const isAnswersFilled = this.checkAnswersNotEmpty(this.questions);
      if (!isAnswersFilled) {
        // 如果有答案为空，给出提示并停止后续操作
        this.$message({
          type: 'warning',
          message: '请完成所有试题后再提交'
        });
        this.submitLoading = false;
        return;
      }
      this.$confirm('是否确认提交试卷?', '考试提交', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        getNow().then(res => {
          let records = []
          this.questions.forEach(q => {
            q.questions.forEach(qq => {
              if (qq.type === '2') {
                qq.answer = qq.answer.sort().toString()
              }
              if (qq.type === '4') {
                let fAnswer = []
                qq.answer.forEach(a => {
                  fAnswer.push({
                    answer: a
                  })
                })
                qq.answer = JSON.stringify(fAnswer)
              }
              let record = {
                questionId: qq.id,
                answer: qq.answer
              }
              records.push(record)
            })
          })
          let params = {
            id: this.taskId,
            startTime: this.startTime,
            endTime: res,
            records
          }
          testTaskSubmit(params).then(() => {
            this.$message({
              type: 'success',
              message: '提交成功'
            });
            this.submitLoading = false
            this.$store.dispatch('tagsView/delView', this.$route)
            this.$router.back()
          })
        })
      })
    },
    checkBg(q) {
      let color = 'background: #d9d9d9'
      if (q.type === '1' || q.type === '3') {
        if (q.answer !== '') {
          color = 'background: #409EFF'
        }
      }
      if (q.type === '2') {
        if (q.answer.length > 0) {
          color = 'background: #409EFF'
        }
      }
      if (q.type === '4') {
        q.answer.some(a => {
          if (a) {
            color = 'background: #409EFF'
            return true
          }
        })
      }
      if (q.type === '5') {
        if (q.answer) {
          color = 'background: #409EFF'
        }
      }
      return color
    }
  }
}
</script>

<style scoped>
.questionView {
  width: 200px;
  position: fixed;
  top: 200px;
  right: 200px;
  z-index: 100;
  background: #ffffff;
}

.question {
  cursor: pointer;
  margin: 5px 5px;
  width: 25px;
  height: 25px;
  color: white;
  border-radius: 3px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  font-weight: 600;
}

.direction {
  display: flex;
  flex-flow: column nowrap;
  align-items: flex-start;
  margin: 10px;
}

::v-deep .el-checkbox__label {
  font-size: 16px;
  color: #333333
}

::v-deep .el-checkbox__inner {
  border: 1px solid #333333;
  width: 16px;
  height: 16px;
}

::v-deep .el-radio__label {
  font-size: 16px;
  color: #333333
}

::v-deep .el-radio__inner {
  border: 1px solid #333333;
  width: 16px;
  height: 16px;
}

</style>
